<template>
    <div class="container">      
      <van-button round type="primary" size="small" @click="exportExcel">导出 Excel</van-button> 
      <h1>JSON 数据：</h1>
      <van-list>
        <van-cell-group inset class="container-item"  v-for="(item,index) in jsonData" :key="index" >
          <van-cell>
            {{item.name}} {{item.age}} {{item.skill}} {{item.telephone}} {{item.address}}
          </van-cell>
        </van-cell-group>
      </van-list>
    </div>
  </template>
  
<script setup lang="ts">
import { onMounted,ref } from "vue"; 
import { getExcelOutJson } from  "@/localhttp/loginApi"
import { toTimeStamp } from "@/utils/dhtools";
import json2Excel from "@/utils/json2Excel"; 

interface JsonTest {
  name: string,
  age: string,
  skill: string,
  telephone: string,
  address: string,
}

// 测试的 JSON 数据
let jsonData = ref<JsonTest[]>([]);

onMounted(() => {
    getExcelOutJson().then((res) => {
      jsonData.value = res.data; 
    });
})

// key -> name 的映射
const excelKeyToName:any = {
  name: "姓名",
  age: "年龄",
  skill: "特长",
  telephone: "电话",
  address: "地址",
};
 
  
// 导出 Excel 文件
const exportExcel = () => {
  // 格式化参数
  const data = jsonData.value.map((item:any) => {
    const newItem: any = {};
    Object.keys(item).forEach(key => {
      newItem[excelKeyToName[key]] = item[key];
    });
    return newItem;
  }); 
  const radomNum= toTimeStamp((new Date()).toString());   
  const excelName = 'Excel' + radomNum  + '.xlsx';
  // 导出 Excel
  json2Excel(data,'sheet1',excelName);
};
</script>

<style lang="scss" scoped>
.container {
    padding: 20px 15px;

    &-item {
        margin: 10px 0px;
    }
}
</style>